package com.alex.wechat.component.codemgr.service.impl;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.jeecgframework.core.util.ApplicationContextUtil;
import org.jeecgframework.core.util.MyClassLoader;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.web.cgform.enhance.CgformEnhanceJavaInter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alex.wechat.app.account.entity.WxAppAccountEntity;
import com.alex.wechat.app.account.service.WxAppAccountServiceI;
import com.alex.wechat.component.codemgr.entity.AuditState;
import com.alex.wechat.component.codemgr.entity.WxCodeUploadMgrEntity;
import com.alex.wechat.component.codemgr.service.WxCodeUploadMgrServiceI;
import com.gomore.jeecg.common.Assert;
import com.gomore.jeecg.common.ServiceException;

@Service("wxCodeUploadMgrService")
@Transactional
public class WxCodeUploadMgrServiceImpl extends CommonServiceImpl
    implements WxCodeUploadMgrServiceI {

  @Autowired
  WxAppAccountServiceI wxAppAccountService;

  public void delete(WxCodeUploadMgrEntity entity) throws Exception {
    super.delete(entity);
    // 执行删除操作增强业务
    this.doDelBus(entity);
  }

  public Serializable save(WxCodeUploadMgrEntity entity) throws Exception {
    Serializable t = super.save(entity);
    // 执行新增操作增强业务
    this.doAddBus(entity);
    return t;
  }

  public void saveOrUpdate(WxCodeUploadMgrEntity entity) throws Exception {
    super.saveOrUpdate(entity);
    // 执行更新操作增强业务
    this.doUpdateBus(entity);
  }

  /**
   * 新增操作增强业务
   * 
   * @param t
   * @return
   */
  private void doAddBus(WxCodeUploadMgrEntity t) throws Exception {
  }

  /**
   * 更新操作增强业务
   * 
   * @param t
   * @return
   */
  private void doUpdateBus(WxCodeUploadMgrEntity t) throws Exception {
  }

  /**
   * 删除操作增强业务
   * 
   * @param id
   * @return
   */
  private void doDelBus(WxCodeUploadMgrEntity t) throws Exception {
  }

  private Map<String, Object> populationMap(WxCodeUploadMgrEntity t) {
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("id", t.getId());
    map.put("create_name", t.getCreateName());
    map.put("create_by", t.getCreateBy());
    map.put("create_date", t.getCreateDate());
    map.put("update_name", t.getUpdateName());
    map.put("update_by", t.getUpdateBy());
    map.put("update_date", t.getUpdateDate());
    map.put("sys_org_code", t.getSysOrgCode());
    map.put("sys_company_code", t.getSysCompanyCode());
    map.put("template_id", t.getTemplateId());
    map.put("ext_json", t.getExtJson());
    map.put("user_version", t.getUserVersion());
    map.put("user_desc", t.getUserDesc());
    map.put("status", t.getStatus());
    map.put("audit_id", t.getAuditId());
    map.put("audit_date", t.getAuditDate());
    map.put("reject_reason", t.getRejectReason());
    map.put("app_id", t.getAppId());
    map.put("component_app_id", t.getComponentAppId());
    return map;
  }

  /**
   * 替换sql中的变量
   * 
   * @param sql
   * @param t
   * @return
   */
  public String replaceVal(String sql, WxCodeUploadMgrEntity t) {
    sql = sql.replace("#{id}", String.valueOf(t.getId()));
    sql = sql.replace("#{create_name}", String.valueOf(t.getCreateName()));
    sql = sql.replace("#{create_by}", String.valueOf(t.getCreateBy()));
    sql = sql.replace("#{create_date}", String.valueOf(t.getCreateDate()));
    sql = sql.replace("#{update_name}", String.valueOf(t.getUpdateName()));
    sql = sql.replace("#{update_by}", String.valueOf(t.getUpdateBy()));
    sql = sql.replace("#{update_date}", String.valueOf(t.getUpdateDate()));
    sql = sql.replace("#{sys_org_code}", String.valueOf(t.getSysOrgCode()));
    sql = sql.replace("#{sys_company_code}", String.valueOf(t.getSysCompanyCode()));
    sql = sql.replace("#{template_id}", String.valueOf(t.getTemplateId()));
    sql = sql.replace("#{ext_json}", String.valueOf(t.getExtJson()));
    sql = sql.replace("#{user_version}", String.valueOf(t.getUserVersion()));
    sql = sql.replace("#{user_desc}", String.valueOf(t.getUserDesc()));
    sql = sql.replace("#{status}", String.valueOf(t.getStatus()));
    sql = sql.replace("#{audit_id}", String.valueOf(t.getAuditId()));
    sql = sql.replace("#{audit_date}", String.valueOf(t.getAuditDate()));
    sql = sql.replace("#{reject_reason}", String.valueOf(t.getRejectReason()));
    sql = sql.replace("#{app_id}", String.valueOf(t.getAppId()));
    sql = sql.replace("#{component_app_id}", String.valueOf(t.getComponentAppId()));
    sql = sql.replace("#{UUID}", UUID.randomUUID().toString());
    return sql;
  }

  /**
   * 执行JAVA增强
   */
  private void executeJavaExtend(String cgJavaType, String cgJavaValue, Map<String, Object> data)
      throws Exception {
    if (StringUtil.isNotEmpty(cgJavaValue)) {
      Object obj = null;
      try {
        if ("class".equals(cgJavaType)) {
          // 因新增时已经校验了实例化是否可以成功，所以这块就不需要再做一次判断
          obj = MyClassLoader.getClassByScn(cgJavaValue).newInstance();
        } else if ("spring".equals(cgJavaType)) {
          obj = ApplicationContextUtil.getContext().getBean(cgJavaValue);
        }
        if (obj instanceof CgformEnhanceJavaInter) {
          CgformEnhanceJavaInter javaInter = (CgformEnhanceJavaInter) obj;
          javaInter.execute(data);
        }
      } catch (Exception e) {
        e.printStackTrace();
        throw new Exception("执行JAVA增强出现异常！");
      }
    }
  }

  @Override
  public void updateByAuditNotification(String originalId, boolean auditSuccess, String reason)
      throws Exception {
    Assert.assertArgumentNotEmpty(originalId, "originId");

    // 查找对应小程序
    WxAppAccountEntity appAccount = wxAppAccountService
        .findUniqueByProperty(WxAppAccountEntity.class, "originalId", originalId);
    if (appAccount == null) {
      throw new ServiceException("未找到小程序账户originalId:" + originalId);
    }

    // 获取当前正在审核的代码
    String hql = "from " + WxCodeUploadMgrEntity.class.getName()
        + " o where o.appId = ? and o.status = ?";
    List<WxCodeUploadMgrEntity> uploadMgrList = findByHql(hql, appAccount.getAppId(),
        AuditState.AUDITING);

    if (uploadMgrList == null || uploadMgrList.size() == 0) {
      throw new ServiceException("未找到appId=" + appAccount.getAppId() + "状态为审核中的代码");
    }
    WxCodeUploadMgrEntity uploadMgr = uploadMgrList.get(0);
    if (auditSuccess) {
      uploadMgr.setStatus(AuditState.PASSED);
    } else {
      uploadMgr.setStatus(AuditState.REJECTED);
      uploadMgr.setRejectReason(reason);
    }

    // 更新状态
    saveOrUpdate(uploadMgr);
  }
}